package com.mjk.common.core.jdbc.health;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.mjk.common.core.jdbc.datasource.IDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

/**
 * bee 数据源 健康检测
 */
@Component
public class BeedbHealthIndicator extends AbstractHealthIndicator {
    @Autowired
    private IDataSource dataSource;
    protected void doHealthCheck(Health.Builder builder) throws Exception {
        Map<String,DataSource> allDataSource = dataSource.getAllDataSource();
        boolean isHealth = true;
        for(Map.Entry<String,DataSource> entry : allDataSource.entrySet()){
            try( Connection connection = entry.getValue().getConnection();){
                builder.withDetail(entry.getKey(),getProduct(connection));
                isHealth= isConnectionValid(connection);
            }catch (Exception e){
                isHealth = false;
                builder.withDetail(entry.getKey(), ExceptionUtil.getMessage(e));
            }
        }
        if(isHealth){
            builder.up();
        }else{
            builder.down();
        }
    }

    private String getProduct(Connection connection) throws SQLException {
        return connection.getMetaData().getDatabaseProductName();
    }

    private Boolean isConnectionValid(Connection connection) throws SQLException {
        return connection.isValid(0);
    }
}
